import { defineStore } from "pinia";

import * as cookies from "@/utils/cache/cookies";
import * as server from '@/api/modules/user';
import * as local from '@/utils/cache/localStorage';

import { getDefaultOrgIds } from "@/utils/user";
import { apiFn } from '@/utils/utilFns';

export const useUserStore = defineStore('userState', {
    state: () => ({
        userInfo: {},
        roles: [],
        isLogout: false,
    }),
    getters: {
        
    },
    actions: {
        setToken(val){
            this.token = val;
            cookies.setToken(val);
        },
        setUser(userInfo){
            this.userInfo = userInfo;
            local.setUser(userInfo);
            
            this.getAuthority();
            this.getOrgList();
            this.getMineList();
        },
        // 获取组织列表
        getOrgList(){
            const params = {
                like: {
                    userOrgId: this.userInfo.orgId
                }
            };
            
            server.getOrganizationList(params)
                .then(res => {
                    const { code, data = [] } = res;
                    if (code === '200') {
                        let orgDatas = [];
                        data.forEach(item => {
                            if(item.parentId === '-1'){
                                orgDatas = [...orgDatas, ...item.children];
                            }else{
                                orgDatas = [...orgDatas, item];
                            }
                        });
                        const { ids, nodes } = getDefaultOrgIds([orgDatas[0]]);
                        local.setItem('orgTreeDatas', orgDatas);
                        local.setItem('defaultOrgIds', ids.join(','));
                        local.setItem('defaultOrgNodes', nodes.join(','));
                    }else{
                        local.setItem('orgTreeDatas', []);
                        local.setItem('defaultOrgIds', '');
                        local.setItem('defaultOrgNodes', '');
                    }
                })
        },
        // 获取用户权限
        getAuthority(){
            const params = {
                sysRoleId: this.userInfo.userRoleBind
            };
            
            server.getAuthority(params)
                .then(res => {
                    if(res) {
                        const authIdArr = res.map(item => item.id);
                        local.setItem('rules', authIdArr);
                    }
                });
        },
        // 获取矿区列表
        getMineList(){
            const params = {
                like: { orgId: this.userInfo.orgId }
            };
            apiFn(server.getMineList, params)
                .then(res => {
                    const { data = [] } = res;
                    if(data.length > 0){
                        data.forEach(item => {
                            const { mapId } = item;
                            item.value = mapId;
                        });
                        local.setItem('mineList', data);
                        local.setItem('defaultIdPath', data[0].id)
                        local.setItem('defaultMapId', data[0].mapId);
                    }else{
                        local.setItem('mineList', []);
                        local.setItem('defaultMapId', '');
                    }
                });
        },
        // 退出登录
        logout () {
            return new Promise((resolve, reject) => {
                apiFn(server.logout, {})
                    .then(res => {
                        const { code } = res;
                        if(code === '200'){
                            this.isLogout = true;
                            this.roles = [];
                            cookies.setToken('');
                            local.setItem('orgTreeDatas', []);
                            local.setItem('defaultOrgIds', '');
                            local.setItem('defaultOrgNodes', []);
                        }
                    }).catch(err => reject(err));
            });
        }
    }
});

